<template>
	<view class="container">
		<button @click="downloadImage">下载图片</button>
		<view class="progress" v-if="progress !== -1">下载进度：{{ progress }}%</view>
		<image :src="imagePath" mode="widthFix" v-if="imagePath"></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imagePath: '',
				progress: -1
			}
		},
		methods: {
			downloadImage() {
				const imageUrl = "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg";

				const downloadTask = uni.downloadFile({
					url: imageUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('图片下载成功，本地路径：', res.tempFilePath);
							this.imagePath = res.tempFilePath;
						} else {
							console.log('图片下载失败，状态码：', res.statusCode);
						}
					},
					fail: (err) => {
						console.log('图片下载失败，错误信息：', err);
					}
				});

				downloadTask.onProgressUpdate((progressRes) => {
					this.progress = progressRes.progress;
					console.log('下载进度：', progressRes.progress + '%');
					console.log('已下载：', progressRes.totalBytesWritten);
					console.log('总大小：', progressRes.totalBytesExpectedToWrite);
				});
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx;
	}

	image {
		width: 100%;
		max-width: 600rpx;
		margin: 20rpx 0;
	}

	.progress {
		margin: 20rpx 0 10rpx 0;
		font-size: 28rpx;
		color: #333;
	}

	button {
		width: 80%;
		appearance: button;
		-webkit-appearance: button;
		padding: 8rpx 0;
		text-align: center;
		border: 1px solid #ddd;
		border-radius: 4rpx;
		background-color: #f8f8f8;
		color: #333;
		font-size: 32rpx;
		text-decoration: none;
	}
</style>